<?php
class Model_User extends Model{
    static protected $_instance =  null;
	/**
     * @return Model_User
     */
	static public function getInstance(){
        if(is_null(self::$_instance))	
           self::$_instance = new self('user');     
        return self::$_instance;   
    }
    /**
     * Get user info
     * @param integer $id
     * @throws Exception
     * @return array
     */
    public function getInfo($id)
    {
        if(empty($id))
            throw new Exception('Need user id');
          
        /*
         * Check cached info
         */    
        $cache = Application::dataCache();    
        if($cache && $data = $cache->load('user_info' . $id))
        	return $data;    

        /*
         * Get user data
         */	
        $sql = $this->_db->select()
					     ->from($this->_dbPrefix . $this->_table)
					     ->where('`id` = '.intval($id))
					     ->limit(1);
        
        $data = $this->_db->fetchRow($sql);

        if(empty($data))
          	return false;

        /*
         * Store cache
         */  
        if($cache)
        	$cache->save($data , 'user_info' . $id);
        	
        return $data;      
    }
    /**
     * (non-PHPdoc)
     * @see Model::remove()
     */
    public function remove($recordId , $log =true){
    	if(parent::remove($recordId , $log)){
    		/*
	         * Check cached info
	         */    
	        $cache = Application::dataCache();  
    		if($cache)
        		$cache->remove('user_info' . $recordId);
    		
    		return true;
    	}
    	return false;
    }
	/**
	 * Check if login form has been posted
	 * @param bolean $admin - optional
	 * @return void
	 */
    public function checkLogin($admin = false){
        $user = Request::post('ulogin', 'login', false);
        $pass = Request::post('upassword' , 'string' , false);

        if($user === false || $pass=== false)
            return;
        
        $pass = Utils::hash($pass);  
         
        $sql = $this->_db->select()
                          ->from($this->_dbPrefix . $this->_table)
                          ->where('`login` =?' , $user)
                          ->where('`pass` =?' , $pass)
                          ->where('`enabled` = 1');
                          
         if($admin)
             $sql->where('`admin` =1');                        
              
         $data = $this->_db->fetchRow($sql);

         if(empty($data))
             return;
         
         if($admin)
             $user = User_Admin::getInstance();   
         else 
             $user = User::getInstance();
         
         $user->setId($data['id']);
         $user->setInfo($data);   
         $user->setAuthorised($admin);            
    }
}